package com.topisv.tms.web.phone;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.BackupTask;
import com.topisv.tms.entity.BackupTaskSku;
import com.topisv.tms.entity.BatchTask;
import com.topisv.tms.entity.LogisticsCompany;
import com.topisv.tms.entity.Permission;
import com.topisv.tms.entity.Role;
import com.topisv.tms.entity.ShopSource;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.Userrole;
import com.topisv.tms.entity.dto.BackupTaskSkuDTO;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.BackupTaskService;
import com.topisv.tms.service.BackupTaskSkuService;
import com.topisv.tms.service.BatchTaskService;
import com.topisv.tms.service.EdiGoodsSkuService;
import com.topisv.tms.service.LogisticsCompanyService;
import com.topisv.tms.service.PermissionService;
import com.topisv.tms.service.ShopSourceService;
import com.topisv.tms.service.account.AccountService;
import com.topisv.tms.utils.DigestsUtils;
import com.topisv.tms.utils.enums.StatusEnums;
import com.topisv.tms.utils.store.GetSkuStoreUtil;

import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/phone")
public class SourcePhoneController {
	private static final Logger log = LoggerFactory.getLogger(SourcePhoneController.class);

	@Autowired
	private BackupTaskService backupTaskService;
	@Autowired
	private BackupTaskSkuService backupTaskSkuService;
	@Autowired
	private AccountService accountService;
	@Autowired
	private BatchTaskService batchTaskService;
	@Autowired
	private ShopSourceService shopSourceService;
	@Autowired
	private EdiGoodsSkuService ediGoodsSkuService;
	@Autowired
	private PermissionService permissionService;
	@Autowired
	private LogisticsCompanyService logisticsCompanyService;
	@Autowired
	private AreaGroupService areaGroupService;
	
	/**
	 * 手机商家端登陆
	 * 
	 * @param username
	 * @param password
	 * @param response
	 */
	@RequestMapping(value = "ajaxLogin", method = RequestMethod.POST)
	public void login(@RequestParam(value = "username") String username,
			@RequestParam(value = "password") String password,
			HttpServletResponse response) {
		Map map = new HashMap();
		ObjectMapper objectMapper = new ObjectMapper();
		JsonGenerator jsonGenerator = null;
		User user = null;
		List<Userrole> userroles = null;
		try {
			user = accountService.findUserByUsername(username);
			if (null == user) {
				map.put("status", 0);
				map.put("content", "该用户不存在");
			} else {
				password = DigestsUtils.getPassWord(password, user.getSalt());
				if (!password.equals(user.getPassword())) {
					map.put("status", 0);
					map.put("content", "密码错误");
					objectMapper.writeValue(response.getWriter(), map);
					return;
				}
				userroles = accountService.findByUserId(user.getId());
				StringBuffer roleName = new StringBuffer("");
				StringBuffer tempFunctionList=new StringBuffer("");
				for (int i = 0; i < userroles.size(); i++) {
					Userrole userrole = userroles.get(i);
					Role role = userrole.getRole();
					String rolename = role.getRolename();
					if ("".equals(roleName.toString())) {
						roleName.append(rolename);
					} else {
						roleName.append(":" + rolename);
					}		
					List<Permission> permissions = permissionService.findAppPermByRoleId(role.getId());
					for (Permission permission : permissions) {
						if (permission!=null) {
							if (!tempFunctionList.toString().contains(permission.getUrlprefix()+":")) {
								tempFunctionList.append(permission.getUrlprefix()+":");
							}
						}
					}
					
				}
				String functionList=tempFunctionList.toString();
				if ("".equals(functionList)||functionList.length()==0) {
					map.put("status", 2);
					map.put("content", "没有功能权限");
					objectMapper.writeValue(response.getWriter(), map);
					return;
				}
				functionList=functionList.substring(0, functionList.length()-1);
				map.put("functionList",functionList);
				map.put("status", 1);
				map.put("jobuuid", user.getJobuuid());
				map.put("roleName", roleName.toString());
				map.put("userType", user.getUserType());
				if(StatusEnums.user_type_customer.getStatus().equals(user.getUserType())){
					map.put("customers", user.getCustomerCode());
				}else{
					map.put("customers", user.getCustomers());//商家
				}
				map.put("areaGroupCodes", user.getAreagroups());//仓库
				List<LogisticsCompany> cmpList = logisticsCompanyService.findAll();
				map.put("cmpList", cmpList);
				List<AreaGroup> warehouseList = null; 
				if (StatusEnums.user_type_customer.getStatus().equals(user.getUserType())) {
					  warehouseList = areaGroupService.loadByCustomerCode(user.getCustomerCode());
				} else if (StatusEnums.user_type_paiu.getStatus().equals(user.getUserType())) {
					  warehouseList = areaGroupService.findByAreaGroups(user.getAreagroups());
				}
				map.put("warehouseList", warehouseList);
			}
			objectMapper.writeValue(response.getWriter(), map);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
		}
	}
	
	@RequestMapping(value = "backupTaskSkuLists")
	public void backupTaskSkuLists(
			@RequestParam(value = "jobuuid") String jobuuid,
			@RequestParam(value = "backupTaskCode") String backupTaskCode,
			HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		List<BackupTaskSku> backupTaskSkus = null;
		BackupTask backupTask=null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			User user=accountService.findUserByJobuuid(jobuuid);
			if(user==null){
				json.put("status", "-1");
				json.put("content", "该用户名不存在");
				out.print(json.toString());
				return;
			}
			backupTask=backupTaskService.findByBackupTaskCode(backupTaskCode);
			backupTaskSkus=backupTaskSkuService.findByBackupTaskCode(backupTaskCode);
			BatchTask batchTask = batchTaskService.findByBatchTaskCode(backupTask.getBatchTaskCode());
			ShopSource shopSource = shopSourceService.findByShopCode(batchTask.getShopSourceCode());//根据店铺编码获取店铺信息
			// 获得库存信息
			if ("ht".equals(shopSource.getOrdenoSourceCode())) {
				GetSkuStoreUtil.setHTSkuStoreCode(backupTaskSkus, shopSource);
			} else if ("ocr".equals(shopSource.getOrdenoSourceCode())) {
				GetSkuStoreUtil.setOCRSkuStoreCode(backupTaskSkus,user.getCustomerCode(),ediGoodsSkuService);
			}

			json.put("status", "1");
			json.put("content", backupTaskSkus);
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			log.error("error",e);
		}
		

	}


	/**
	 * 显示拣货列表
	 * 
	 * @param backupTaskCode
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "ajaxBackupTaskLists")
	public void backupTaskLists(
			@RequestParam(value = "jobuuid") String jobuuid,
			HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		String status = "pending";// 未处理的拣货任务
		List<BackupTask> backupTasks = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			backupTasks = backupTaskService.findByPickStatusAndJobuuid(status,jobuuid);
			backupTasks.addAll(backupTaskService.findByPickStatusAndJobuuid(status, "pending"));
			json.put("status", "1");
			json.put("content", backupTasks);
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			log.error("error",e);
		}
		out.print(json.toString());

	}

	/**
	 * 商品拣货
	 * 
	 * @param backupTaskCode
	 * @param sku
	 * @param number
	 * @param response
	 */
	@RequestMapping(value = "ajaxPickingSku")
	public void ajaxPickingSku(
			@RequestParam(value = "backupTaskCode") String backupTaskCode,
			@RequestParam(value = "sku") String sku,
			@RequestParam(value = "number") int number,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			BackupTaskSkuDTO backupTaskSkuDTO = backupTaskService
					.pickBackupTaskSku(backupTaskCode, sku, number);
			if (backupTaskSkuDTO == null) {
				json.put("status", "-1");
				json.put("content", "拣货失败:该商品不属于该拣货任务");
				out.print(json.toString());
				return;
			}

			if ("-1".equals(backupTaskSkuDTO.getStatus())) {
				json.put("status", "-1");
				json.put("content", backupTaskSkuDTO.getReserve());
			} else {
				json.put("status", "1");
				json.put("content", backupTaskSkuDTO.getReserve());
			}
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			log.error("error",e);
		}
	}
}
